package com.inspectortime.mail.service;

import org.springframework.mail.MailMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.util.StringUtils;

import com.inspectortime.mail.mailer.Mailer;

import freemarker.template.Configuration;

/**
 * Allows for mail to be sent based on freemarker templates either from
 * persisted EmailTemplate templates or from files
 * 
 * @author mkvalsvik
 * 
 */
public class FreemarkerMailServiceImpl implements MailService {

	private Configuration freemarkerConfiguration;
	private Mailer mailer;
	private String defaultFrom;

	public FreemarkerMailServiceImpl(Mailer mailer, Configuration freemarkerConfiguration, String defaultFrom) {
		this.mailer = mailer;
		this.freemarkerConfiguration = freemarkerConfiguration;
		this.defaultFrom = defaultFrom;
	}
	
	private void validate(AbstractMailMessage serviceMessage) throws EmailDeliveryException {
		if (!StringUtils.hasText(serviceMessage.getTo())) {
			throw new EmailDeliveryException("Missing 'to' field");
		}
		if (!StringUtils.hasText(serviceMessage.getSubject())) {
			throw new EmailDeliveryException("Missing 'subject' field");
		}
		if (!StringUtils.hasText(serviceMessage.getBody())) {
			throw new EmailDeliveryException("Missing 'body' field");
		}
	}

	public void send(AbstractMailMessage serviceMessage) throws EmailDeliveryException {		
		serviceMessage.processTemplates(freemarkerConfiguration);
		this.validate(serviceMessage);
		
		MailMessage message = new SimpleMailMessage();
		message.setSubject(serviceMessage.getSubject());
		message.setTo(serviceMessage.getTo());
		if (serviceMessage.getFrom() != null) {
			message.setFrom(serviceMessage.getFrom());	
		} else {
			message.setFrom(defaultFrom);
		}
		message.setReplyTo(serviceMessage.getReplyTo());
		message.setText(serviceMessage.getBodyHtml());

		this.mailer.sendMail(message);
	}

}
